package com.qlk.vorder.porxy.impl;

import com.qlk.common.utils.serialize.JsonHelper;
import com.qlk.vorder.porxy.QueryRefundProxy;
import com.qlk.vorder.porxy.dto.QueryRefundResponse;
import com.qlk.vorder.porxy.dto.RefundResponse;
import com.qlk.vorder.utils.http.HttpUtil;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.jboss.resteasy.util.Encode;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhaoyanan on 2016/8/4.
 */
@Component
public class QueryRefundProxyImpl implements QueryRefundProxy {

    private static final Log LOG = LogFactory.getLog(QueryRefundProxyImpl.class);

    public List<QueryRefundResponse> getRefundListByOrderid(String orderid){
//        String url = PropertiesHelper.newInstance().getValue("goods.to.pdc.category.ws.url");
        try {
        	  String url = "http://ops.oss.7lk.com/api/refund/get_order";
              PostMethod postMethod = new PostMethod(url);
              LOG.info("创建退款单URL:" + url + "请求参数" + orderid);
      		  // 然后把Soap请求数据添加到PostMethod中
      		  NameValuePair[] dataStr = {  
      	               new NameValuePair("order_ids", orderid),  
      	       }; 
      		// 最后生成一个HttpClient对象，并发出postMethod请求
      		postMethod.setRequestBody(dataStr);
      		HttpClient httpClient = new HttpClient();
      		int statusCode = httpClient.executeMethod(postMethod);
      		LOG.info("创建退款接口返回状态statusCode："+statusCode);
        	String response = postMethod.getResponseBodyAsString();
            if(null != response && response.contains("code")){
            	//response = Encode.decode(response);
                LOG.info("QueryRefundProxyImpl getRefundListByOrderid result##" + Encode.decode(response));
                ObjectMapper mapper = new ObjectMapper();
                JsonNode root = mapper.readTree(response);
                JsonNode codeJN = root.path("code");
                JsonNode data = root.path("data");
                int code = codeJN.asInt();
                if(code == 0){
                    LOG.info("查询退款信息成功.订单号：");
                    //String body = data.asText();
                    String body = data.toString();
                    List<QueryRefundResponse> queryRefundResponseList = JsonHelper.toList(body,QueryRefundResponse.class);
                    return queryRefundResponseList;
                }else{
                    LOG.error("查询退款信息失败.###"+response);
                    return null;
                }
            }
        } catch (Exception e) {
            LOG.error("QueryRefundProxyImpl#getRefundListByOrderid has a error." + e);
        }
        return null;
    }

}
